package com.changy.ai_tutor_for_dm.tools;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Slf4j
@Component
public class AliyunOSSOperator {

    // Endpoint以华东1（杭州）为例，填写为https://oss-cn-hangzhou.aliyuncs.com，其它Region请按实际情况填写。
    // 深圳节点url
    private String endpoint = "https://oss-cn-shenzhen.aliyuncs.com";
    private String bucketName = "atfd";
    // 关于OSS支持的Region与Endpoint的对应关系，请参见https://www.alibabacloud.com/help/zh/oss/user-guide/regions-and-endpoints。
    private String region = "cn-shenzhen";

    /**
     * 上传文件
     * @param content 二进制文件内容
     * @param pathName 例如‘/resource'
     * @param originalFilename 文件名
     * @return 文件的url
     * @throws Exception
     */
    public String upload(byte[] content, String pathName, String originalFilename) throws Exception {
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        //生成一个新的不重复的文件名
        String newFileName = UUID.randomUUID() + originalFilename;
        String objectName = pathName + newFileName;

        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 显式声明使用 V4 签名算法
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();
        try {
            PutObjectResult result = ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));
            String encodedObjectName = URLEncoder.encode(objectName, StandardCharsets.UTF_8.toString());
            return "https://atfd.oss-cn-shenzhen.aliyuncs.com/" + encodedObjectName;
        } finally {
            ossClient.shutdown();
        }
    }
}
